package ldk.util.logger;

import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;

/**
 * Created by ldkxingzhe@163.com on 2017/5/27.
 */
public class LogUtils {
    private LogUtils(){}

    public static String logLevel2Str(int logLevel){
        String logLevelStr = null;
        switch (logLevel){
            case Log.VERBOSE:
                logLevelStr = "VERBOSE";
                break;
            case Log.DEBUG:
                logLevelStr = "DEBUG";
                break;
            case Log.INFO:
                logLevelStr = "INFO";
                break;
            case Log.WARN:
                logLevelStr = "WARN";
                break;
            case Log.ERROR:
                logLevelStr = "ERROR";
                break;
            default:
                logLevelStr = "OTHERS";
        }
        return logLevelStr;
    }

    /**
     * Copied from "android.util.Log.getStackTraceString()" in order to avoid usage of Android stack
     * in unit tests.
     * @return Stack trace in form of String
     */
    public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }
}
